package com.cykj.shop.controller;

import com.cykj.common.core.web.controller.BaseController;
import com.cykj.common.core.web.domain.AjaxResult;
import com.cykj.common.core.web.page.TableDataInfo;
import com.cykj.common.log.annotation.Log;
import com.cykj.common.log.enums.BusinessType;
import com.cykj.shop.domain.BsDeliveryFeeRule;
import com.cykj.shop.domain.dto.DeliveryFeeRuleDto;
import com.cykj.shop.service.IDeliveryFeeRuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
import java.util.List;

/**
 * 配送费规则Controller
 * 
 * @author 泽日
 * @date 2025-01-20
 */
@RestController
@RequestMapping("/deliveryFeeRule")
public class DeliveryFeeRuleController extends BaseController {
    
    @Autowired
    private IDeliveryFeeRuleService deliveryFeeRuleService;
    
    /**
     * 查询配送费规则列表（带分页）
     */
    @GetMapping("/list")
    public TableDataInfo list(BsDeliveryFeeRule deliveryFeeRule) {
        startPage();
        List<BsDeliveryFeeRule> list = deliveryFeeRuleService.selectDeliveryFeeRuleList(deliveryFeeRule);
        return getDataTable(list);
    }
    
    /**
     * 查询配送费规则列表（不分页）
     */
    @GetMapping("/listAll")
    public AjaxResult listAll(BsDeliveryFeeRule deliveryFeeRule) {
        List<BsDeliveryFeeRule> list = deliveryFeeRuleService.selectDeliveryFeeRuleList(deliveryFeeRule);
        return success(list);
    }
    
    /**
     * 根据商家ID查询配送费规则列表
     */
    @GetMapping("/shop/{shopId}")
    public AjaxResult getByShopId(@PathVariable("shopId") Long shopId) {
        List<BsDeliveryFeeRule> list = deliveryFeeRuleService.selectDeliveryFeeRuleByShopId(shopId);
        return success(list);
    }
    
    /**
     * 根据商家ID查询启用的配送费规则
     */
    @GetMapping("/shop/{shopId}/active")
    public AjaxResult getActiveByShopId(@PathVariable("shopId") Long shopId) {
        BsDeliveryFeeRule rule = deliveryFeeRuleService.selectActiveDeliveryFeeRuleByShopId(shopId);
        return success(rule);
    }
    
    /**
     * 根据配送费规则ID获取详细信息
     */
    @GetMapping("/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        BsDeliveryFeeRule rule = deliveryFeeRuleService.selectDeliveryFeeRuleById(id);
        return success(rule);
    }
    
    /**
     * 新增配送费规则
     */
    @PostMapping
    @Log(title = "配送费规则", businessType = BusinessType.INSERT)
    public AjaxResult add(@Validated @RequestBody DeliveryFeeRuleDto ruleDto) {
        try {
            return toAjax(deliveryFeeRuleService.insertDeliveryFeeRule(ruleDto));
        } catch (Exception e) {
            logger.error("新增配送费规则失败", e);
            return error(e.getMessage());
        }
    }
    
    /**
     * 修改配送费规则
     */
    @PutMapping
    @Log(title = "配送费规则", businessType = BusinessType.UPDATE)
    public AjaxResult edit(@Validated @RequestBody DeliveryFeeRuleDto ruleDto) {
        try {
            return toAjax(deliveryFeeRuleService.updateDeliveryFeeRule(ruleDto));
        } catch (Exception e) {
            logger.error("修改配送费规则失败", e);
            return error(e.getMessage());
        }
    }
    
    /**
     * 删除配送费规则
     */
    @DeleteMapping("/{ids}")
    @Log(title = "配送费规则", businessType = BusinessType.DELETE)
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(deliveryFeeRuleService.deleteDeliveryFeeRuleByIds(ids));
    }
    
    /**
     * 启用配送费规则
     */
    @PutMapping("/enable/{id}")
    @Log(title = "配送费规则", businessType = BusinessType.UPDATE)
    public AjaxResult enable(@PathVariable("id") Long id) {
        try {
            return toAjax(deliveryFeeRuleService.enableDeliveryFeeRule(id));
        } catch (Exception e) {
            logger.error("启用配送费规则失败", e);
            return error(e.getMessage());
        }
    }
    
    /**
     * 禁用配送费规则
     */
    @PutMapping("/disable/{id}")
    @Log(title = "配送费规则", businessType = BusinessType.UPDATE)
    public AjaxResult disable(@PathVariable("id") Long id) {
        try {
            return toAjax(deliveryFeeRuleService.disableDeliveryFeeRule(id));
        } catch (Exception e) {
            logger.error("禁用配送费规则失败", e);
            return error(e.getMessage());
        }
    }
    
    /**
     * 计算配送费
     */
    @GetMapping("/calculate")
    public AjaxResult calculateDeliveryFee(@RequestParam("shopId") Long shopId,
                                          @RequestParam("distance") BigDecimal distance) {
        try {
            BigDecimal deliveryFee = deliveryFeeRuleService.calculateDeliveryFee(shopId, distance);
            return success(deliveryFee);
        } catch (Exception e) {
            logger.error("计算配送费失败", e);
            return error(e.getMessage());
        }
    }
    
    /**
     * 检查规则名称是否存在
     */
    @GetMapping("/checkRuleName")
    public AjaxResult checkRuleName(@RequestParam("ruleId") String ruleId,
                                   @RequestParam("shopId") Long shopId,
                                   @RequestParam(value = "excludeId", required = false) Long excludeId) {
        boolean exists = deliveryFeeRuleService.checkRuleNameExists(ruleId, shopId, excludeId);
        return success(!exists); // 返回true表示可以使用，false表示已存在
    }
}
